import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/assets/assets.dart';
import 'package:pornhub_app/assets/styles.dart';
import 'package:pornhub_app/components/pay/pay_utils.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';

import 'model/recharge_type_model.dart';

/// 通用支付页面
/// 具体UI样式排版可以自行改动
class PayView extends StatefulWidget {
  final double amount; //支付金额
  final int payId; //购买的ID
  final int payNumber; //购买的数量
  //购买类型 (1-常规充值; 2-购买VIP; 3-购买金币; 4-购买门票; 5-购买AI_VIP会员)
  final int purType;
  final List<RechargeTypeModel> payType; //支付类型
  final int source; //来源 0:平台

  final bool isShowBalance; //是否显示余额
  final bool isAddBalancePay; //是否添加余额支付
  final bool isDefaultSelectedFirst; //是否默认选中第一个
  final bool isShowNotPayType; //是否显示没有支付方式
  final bool isShowPayFeedback; //是否显示支付问题反馈
  final GestureTapCallback? onTapPayFeedback; //支付问题反馈点击事件
  final Function(RechargeTypeModel purType)? onPaySelected; //选择的支付类型回调
  final Function()? onPaySuccess; //成功后才回调

  const PayView({
    super.key,
    required this.amount,
    required this.payId,
    this.payNumber = 1,
    required this.purType,
    required this.payType,
    this.source = 0,
    this.isShowBalance = true,
    this.isAddBalancePay = true,
    this.isDefaultSelectedFirst = true,
    this.isShowNotPayType = true,
    this.isShowPayFeedback = true,
    this.onTapPayFeedback,
    this.onPaySelected,
    this.onPaySuccess,
  });

  @override
  State<PayView> createState() => PayViewState();
}

class PayViewState extends State<PayView> {
  late double amount; //支付金额
  late int payId; //购买的ID
  late int payNumber; //购买的数量
  late int purType; //购买类型
  late double balance; //余额
  late int source; //来源
  late List<RechargeTypeModel> payType; //支付类型
  final currentPayType = RechargeTypeModel.empty().obs;

  final userService = Get.find<UserService>();

  @override
  void initState() {
    super.initState();
    amount = widget.amount;
    payId = widget.payId;
    payNumber = widget.payNumber;
    purType = widget.purType;
    payType = widget.payType;
    balance = userService.assets.bala ?? 0;
    source = widget.source;

    if (widget.isAddBalancePay) {
      if (!payType.any((element) => element.payMent == '0001')) {
        payType.add(RechargeTypeModel.balance());
      }
    }

    if (widget.isDefaultSelectedFirst) {
      currentPayType.value = payType.first;
    }
  }

  @override
  void didUpdateWidget(PayView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.payType != oldWidget.payType) {
      payType = widget.payType;
      if (widget.isAddBalancePay) {
        if (!payType.any((element) => element.payMent == '0001')) {
          payType.add(RechargeTypeModel.balance());
        }
      }

      if (widget.isDefaultSelectedFirst) {
        currentPayType.value = payType.first;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    /// 使用Wrap包裹，可以让子widget自适应高度
    return Wrap(
      children: [
        // Column(
        //   children: [
        //     _buildPayTypesView(),
        //     20.verticalSpace,
        //     _buildPayButtonView(),
        //   ],
        // ),
        _buildPayTypesView(),
        // _buildContentView(),
      ],
    );
  }

  /// 弹窗的内容
  _buildContentView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: Styles.borderRaidus.mTop,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题
          _buildTitleView(),
          5.verticalSpace,
          const Divider(height: 0.5, thickness: 0),
          // 支付金额
          15.verticalSpace,
          _buildAmountView(),
          // 支付选项
          15.verticalSpace,
          _buildPayTypesView(),
          //支付提示
          20.verticalSpace,
          _buildTipsView(),
          // 支付按钮
          20.verticalSpace,
          _buildPayButtonView(),
          // 支付问题反馈
          15.verticalSpace,
          _buildPayFeedbackView(),
          30.verticalSpace,
        ],
      ),
    );
  }

  /// 标题
  _buildTitleView() {
    return SizedBox(
      width: double.infinity,
      height: 50.w,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Text(
            '选择支付方式',
            style: TextStyle(
              color: COLOR.color_333333,
              fontSize: 16.w,
              fontWeight: FontWeight.bold,
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            bottom: 0,
            child: Image.asset(
              Assets.iconClose,
              width: 14.w,
              height: 14.w,
            ).onTap(() => Get.back()),
          ),
        ],
      ),
    );
  }

  /// 支付金额
  _buildAmountView() {
    return Align(
      alignment: Alignment.centerLeft,
      child: EasyRichText(
        '支付金额：${widget.amount}元',
        defaultStyle: TextStyle(
          color: COLOR.color_666666,
          fontSize: 12.w,
        ),
        patternList: [
          EasyRichTextPattern(
            targetString: '${widget.amount}元',
            style: TextStyle(
              color: COLOR.color_F22F40,
              fontSize: 12.w,
            ),
          )
        ],
      ),
    );
  }

  /// 支付选项
  _buildPayTypesView() {
    return payType.isEmpty
        ? widget.isShowNotPayType
            ? _buildNotPayTypeView()
            : const SizedBox.shrink()
        : ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            padding: EdgeInsets.zero,
            separatorBuilder: (context, index) => 15.verticalSpace,
            itemCount: payType.length,
            itemBuilder: (BuildContext context, int index) {
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  currentPayType.value = payType[index];
                  widget.onPaySelected?.call(currentPayType.value);
                },
                child: Obx(() => _buildPayOptionsItemView(
                    payType[index], currentPayType.value == payType[index])),
              );
            },
          );
  }

  /// 没有支付方式
  _buildNotPayTypeView() {
    return Container(
      width: double.infinity,
      height: 50.w,
      alignment: Alignment.center,
      child: Text(
        "暂无支付方式",
        style: TextStyle(color: Colors.grey, fontSize: 14.sp),
      ),
    );
  }

  /// 支付选项Item
  _buildPayOptionsItemView(RechargeTypeModel rechargeType, bool isSelected) {
    String icon;
    if (rechargeType.isAlipay) {
      icon = Assets.iconAli;
    } else if (rechargeType.isWechat) {
      icon = Assets.iconWx;
    } else if (rechargeType.isUnion) {
      icon = Assets.iconYsf;
    } else {
      icon = Assets.iconPayBalance;
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            Image.asset(icon, width: 32.w, height: 32.w),
            10.horizontalSpace,
            Text(
              rechargeType.name,
              style: TextStyle(
                color: COLOR.white,
                fontSize: 16.w,
                fontWeight: FontWeight.w500,
              ),
            ),
            rechargeType.payMent == "0001" && widget.isShowBalance
                ? Text(
                    '(${balance.toStringAsFixed(2)})',
                    style: TextStyle(
                      color: COLOR.color_666666,
                      fontSize: 16.w,
                      fontWeight: FontWeight.w500,
                    ),
                  )
                : const SizedBox.shrink(),
          ],
        ),
        Image.asset(
          isSelected ? Assets.iconChecked : Assets.iconCheck,
          width: 22.w,
          height: 22.w,
        ),
      ],
    );
  }

  /// 支付提示
  _buildTipsView() {
    final style = TextStyle(
      color: COLOR.color_666666,
      fontSize: 10.w,
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('支付提示',
            style: TextStyle(
              color: COLOR.color_333333,
              fontSize: 12.w,
            )),
        Text('1.跳转后请及时付款，超时支付无法到账，需要重新发起', style: style),
        Text('2.每天发起支付不可超过5次，连续发起且未支付，当心账号将回加入黑名单', style: style),
        Text('3.支付通道在夜间比较忙碌，为保证您的体验，尽量选择白天支付', style: style),
        Text('4.当前支付方式无法完成支付时，请切换不同支付方式尝试', style: style),
      ].joinHeight(8.w),
    );
  }

  /// 支付按钮
  _buildPayButtonView() {
    return GestureDetector(
      onTap: () {
        PayUtils.checkPay(
          amount: widget.amount,
          payNumber: widget.payNumber,
          purType: widget.purType,
          source: widget.source,
          payId: widget.payId,
          balance: balance,
          currentPayType: currentPayType.value,
          onSuccess: () {
            userService.updateAll();
            widget.onPaySuccess?.call();
          },
        );
      },
      child: Container(
        width: double.infinity,
        height: 40.w,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: COLOR.color_FF9000,
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Text(
          "立即支付",
          style: TextStyle(color: COLOR.white, fontSize: 16.sp),
        ),
      ),
    );
  }

  /// 支付问题反馈
  _buildPayFeedbackView() {
    return Container(
      child: !widget.isShowPayFeedback
          ? const SizedBox.shrink()
          : Center(
              child: RichText(
                  text: TextSpan(
                children: [
                  TextSpan(
                      text: '支付问题反馈，点击联系',
                      style: TextStyle(
                          color: COLOR.color_666666, fontSize: 12.sp)),
                  TextSpan(
                    text: '在线客服',
                    style:
                        TextStyle(color: COLOR.color_F52443, fontSize: 12.sp),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        if (widget.onTapPayFeedback == null) {
                          kOnLineService();
                        } else {
                          widget.onTapPayFeedback?.call();
                        }
                      },
                  ),
                ],
              )),
            ),
    );
  }
}
